package drexel.loading;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import drexel.db.DataAccess;
import drexel.marshalling.DOMXMLMarshaller;
import drexel.marshalling.Marshaller;
import drexel.marshalling.UnmarshallingException;

public class FileMovieLoader implements MovieLoader, LoadingNotifier {
	
	private String directory = null;
	private int outstandingFileCounter = 0;
	private List errors = new ArrayList();
	private List workers = new ArrayList();
	
	public FileMovieLoader (String directory) {
		
		this.directory = directory;
	}

	public void loadMovies(List connections) {
		
		LoadingQueue queue = new LoadingQueue();
		
		startWorkers(connections, queue);
		
		File folder = new File(directory);
		
		File[] files = folder.listFiles(new FileFilter() {
			
			public boolean accept(File file) {
				
				return (file.getName().endsWith(".xml"));
			}
		});
		
		outstandingFileCounter = files.length;
		
		System.out.println("Processing " + outstandingFileCounter + " Files");

		for (int i = 0; i < files.length; i++) {
				
			File file = files[i];
			
			queue.addMovieFile(file);
		}
		
		while (outstandingFileCounter > 0) {
			
			try {
				
				Thread.sleep(3000);
				
			} catch (InterruptedException e) { }
		}
		
		System.out.println("\nProcessing Complete");
		
		if (errors.size() > 0) {
			
			System.out.println("\nErrors During Loading\n");
			
			for (int i = 0; i < errors.size(); i++) {
				
				System.out.println(errors.get(i));
			}
			
			System.out.println("\n");
		}
		
		stopWorkers();
		
		try {
			
			Thread.sleep(3000);
			
		} catch (InterruptedException e) { }
	}

	public synchronized void complete() {
		
		outstandingFileCounter--;
	}

	public synchronized void error(String message) {
		
		outstandingFileCounter--;
		
		errors.add(message);
	}
	
	private void startWorkers(List connections, LoadingQueue queue) {
		
		for (int i = 0; i < connections.size(); i++) {
			
			LoadingWorker worker = new LoadingWorker(queue, this, 
				(DataAccess) connections.get(i), new DOMXMLMarshaller());
			
			workers.add(worker);
			
			worker.start();
		}
	}
	
	private void stopWorkers() {
		
		for (int i = 0; i < workers.size(); i++) {
		
			LoadingWorker worker = (LoadingWorker) workers.get(i);
			
			worker.shutdown();
		}
	}
}
